<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// import Joomla controllerform library
jimport('joomla.application.component.controllerform');
 
/**
 * Category Controller
 */
class ShopControllerCategory extends JControllerForm
{
	public function save(){
	// get params
		$id =  JRequest::getVar('id');
		$old_parent = JRequest::getVar('old_parent');
		$parent_id = JRequest::getVar('parent_id',0);
		//------------------
		JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . '/tables');
		$row = JTable::getInstance('Category','ShopTable');
		$row->bind(JRequest::get('post'));	
		
	// check diffrent parent old != parent curen upate 
	if($old_parent != $parent_id){
		//------------
			// lay thong tin node hien tai
		$db =& JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select('*');
		$query->from('#__shop_category');
		$query->where('id = '.$id);
		$db->setQuery((string)$query);
		$old_node = $db->loadObject();
		
		// NODE PARENT NULL NOT FOUND 
		if($old_node == null){
			$this->setMessage(JText::_('COM_SHOP_EDIT_NOT_FOUNT_ID_PARENT'));
			$this->setRedirect('index.php?option=com_shop&view=categories');
			return;
		}
		// thong tin node can di chuyen
		$node_pos_left = $old_node->lft;
		$node_pos_right = $old_node->rgt;
		$node_id = $old_node->id;
		$node_size = ($old_node->rgt - $old_node->lft) + 1;
		$node_level = $old_node->level;

		// lay thong tin node di chuyen toi
		$query->clear();
		$query->select('*');
		$query->from('#__shop_category');
		$query->where('id = '.$parent_id);
		$db->setQuery((string)$query);
		$new_node = $db->loadObject();
		// NODE PARENT NULL NOT FOUND 
		if($new_node == null){
			$this->setMessage(JText::_('COM_SHOP_EDIT_NOT_FOUNT_ID_PARENT_NEW'));
			$this->setRedirect('index.php?option=com_shop&view=categories');
			return;
		}
		
		// thong tin node di chuyen  toi
		$parent_id = $new_node->id;
		$parent_pos_left = $new_node->lft;
		$parent_pos_right = $new_node->rgt;
		$parent_size = ($new_node->rgt - $new_node->lft) + 1;
		$parent_level = $new_node->level;
		
		
		//check move parent to child
		if($node_pos_left < $parent_pos_left && $node_pos_right > $parent_pos_right && $node_level < $parent_level && $parent_id != 0){
			$this->setMessage(JText::_('COM_SHOP_ERROR_MOVE_PARENT_TO_CHILD'));
			$this->setRedirect('index.php?option=com_shop&view=categories');
			return;
		}
		
		// setp 5: update level for node new 
		$level_size = $parent_level - $node_level + 1;
		$query->clear();
		$query->update('#__shop_category');
		$query->set('level = level + '.$level_size);
		$query->where('lft >= '.$node_pos_left);
		$query->where('rgt <= '.$node_pos_right);
		$db->setQuery((string)$query);
		$db->query();
		
		
		//step 1 --- temporary "remove" moving node 
		$query->clear();
		$query->update('#__shop_category');
		$query->set('lft = 0 - lft, rgt = 0 - rgt');
		$query->where('lft >= '.$node_pos_left.' AND rgt <='.$node_pos_right);
		$db->setQuery((string)$query);
		$db->query();
		//step 2: decrease left and/or right position values of currently 'lower' items (and parents)
		
		$query->clear();
		$query->update('#__shop_category');
		$query->set('lft = lft - '.$node_size);
		$query->where('lft > '.$node_pos_right);
		$db->setQuery((string)$query);
		$db->query();
		
		$query->clear();
		$query->update('#__shop_category');
		$query->set('rgt = rgt - '.$node_size);
		$query->where('rgt > '.$node_pos_right);
		$db->setQuery((string)$query);
		$db->query();
		//step 3: increase left and/or right position values of future 'lower' items (and parents)
		$query->clear();
		$query->update('#__shop_category');
		$query->set('lft = lft + '.$node_size);
		$query->where(' lft >= '.($parent_pos_right > $node_pos_right?$parent_pos_right - $node_size:$parent_pos_right));
		$db->setQuery((string)$query);
		$db->query();
				
		$query->clear();
		$query->update('#__shop_category');
		$query->set('rgt = rgt + '.$node_size);
		$query->where('rgt >= '.($parent_pos_right > $node_pos_right?$parent_pos_right - $node_size:$parent_pos_right));
		$db->setQuery((string)$query);
		$db->query();
		// step 4: move node (ant it's subnodes) and update it's parent item id 
		
		$query->clear();
		$query->update('#__shop_category');
		$query->set('lft = 0 - lft + '.($parent_pos_right > $node_pos_right?$parent_pos_right - $node_pos_right -1:$parent_pos_right - $node_pos_right - 1 + $node_size));
		$query->set('rgt = 0 - rgt + '.($parent_pos_right > $node_pos_right?$parent_pos_right - $node_pos_right - 1:$parent_pos_right - $node_pos_right - 1 + $node_size));
		$query->where('lft <= 0 - '.$node_pos_left);
		$query->where('rgt >= 0 - '.$node_pos_right);
		$db->setQuery((string)$query);
		$db->query();

		$query->clear();
		$query->update('#__shop_category');
		$query->set('parent_id = ' .$parent_id);
		$query->where('id = '.$node_id);
		$db->setQuery((string)$query);
		$db->query();
		}
		//-------------- check upload file ----------
		include  JPATH_COMPONENT_ADMINISTRATOR . DS . "class.upload.php";
		$img_path = JPATH_SITE . DS . 'images' . DS . 'image_category' .DS;
		
		$img = new Upload($_FILES['upload_file']);
		$new_img_name = $this->name_id_element($row->alias.rand(1,9));
		
		$uploaded = false;
		if ($img->uploaded) {	  					
			//--- upload image origin
			$img->image_convert = 'jpg';
			$img->file_new_name_body = $new_img_name;
			$img->Process($img_path);
			
			// resize image thumb
			$img->file_new_name_body = $new_img_name;
			$img->image_resize = true;
			$img->image_convert = 'jpg';
			$img->image_x = 160;
			$img->image_ratio_y = true;
			$img->Process($img_path.'thumb'.DS);
			if ($img->processed) {
				$row->image = $new_img_name.'.jpg';
				$uploaded = true;
			}
		}
		$img = JRequest::getVar('image');
		if($uploaded == true && $img != ''){
			$this->deleteFile($img_path,$img);
			$this->deleteFile($img_path.'thumb'.DS,$img);
		}
		//-------------- end upload file  -----------
		// end check node parent diffrent
		$store = $row->store();
		if (!$store) {
					echo  "<script>alert({$row->getError()});window.history.go(-1)</script>\n";
		}
	 	if($store){
			$this->setMessage(JText::_('COM_SHOP_UPDATE_SUCCESS'));
			$this->setRedirect('index.php?option=com_shop&view=categories'); 
		}
		else
		{
			$this->setMessage(JText::_('COM_SHOP_UPDATE_ERROR'));
			$this->setRedirect('index.php?option=com_shop&view=categories'); 
		} 
	}
	/**
	* function get element extention name for image
	*/
	public function name_id_element($string = null) {
    	$string = trim($string);
    	$string = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $string);
    	$string = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $string);
    	$string = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $string);
    	$string = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $string);
    	$string = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $string);
    	$string = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $string);
    	$string = preg_replace("/(đ)/", 'd', $string);

    	$string = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $string);
    	$string = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $string);
    	$string = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $string);
    	$string = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $string);
    	$string = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $string);
    	$string = preg_replace("/(\'|\")/", '', $string);
    	$string = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $string);
    	$string = preg_replace("/(Đ)/", 'D', $string);
    	$string = str_replace("--", '_', $string);
    	$string = str_replace("--", '_', $string);
    	$string = str_replace("--", '_', $string);
        $string = str_replace("-", '_', $string);

        $string = str_replace(" ", '_', $string);
         $string = str_replace("/", '_', $string);
    	return $string;
    }
	/**
	*
	*
	*	delete file on directory
	*/
	function deleteFile($path, $filename){
		$upfile = $path . $filename;
		if (file_exists($upfile)){
			unlink($upfile);
		}
	}
}
